﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.Configuration;
using System.Diagnostics;

namespace olierFrm.GeneralCache
{
    public class Cache
    {

        private static string _CacheType;


        public static bool Add(string key, object value)
        {
            if (CacheType == null)
            {
                return false;
            }
            if (CacheType == "Memcached")
            {
                return new MemcachedCache().Add(key, value, (CacheItemPolicy)null, null);
            }
            CacheItemPolicy cip = new CacheItemPolicy
            {
                AbsoluteExpiration = new DateTimeOffset(DateTime.MaxValue)
            };
            return new MemoryCacheBuilder().GetInstance().Add(key, value, cip, null);
        }

        public static object Get(string key)
        {
            if (CacheType == null)
            {
                return null;
            }
            if (CacheType == "Memcached")
            {
                return new MemcachedCache().Get(key, null);
            }
            return new MemoryCacheBuilder().GetInstance().Get(key, null);
        }

        public static bool KeyExists(string key)
        {
            if (CacheType == null)
            {
                return false;
            }
            if (CacheType == "Memcached")
            {
                return new MemcachedCache().Contains(key, null);
            }
            return new MemoryCacheBuilder().GetInstance().Contains(key, null);
        }


        private static string CacheType
        {
            get
            {
                if (_CacheType == null)
                {
                    if (ConfigurationManager.AppSettings["CacheType"] == null)
                    {
                        #if (DEBUG)
                        return null;
                        #endif
                        throw new Exception("在 Web.config 文件的 appSettings 节点中 CacheType 格式错误。\r\n <add key=\"CacheType\" value=\"Memcached\"/> 或 <add key=\"CacheType\" value=\"MemoryCache\"/>");

                    }
                    _CacheType = ConfigurationManager.AppSettings["CacheType"];
                    if ((_CacheType != "Memcached") && (_CacheType != "MemoryCache"))
                    {
                        throw new Exception("在 Web.config 文件的 appSettings 节点中 CacheType 格式错误。\r\n <add key=\"CacheType\" value=\"Memcached\"/> 或 <add key=\"CacheType\" value=\"MemoryCache\"/>");
                    }
                }
                return _CacheType;
            }
        }
    }



}
